package _17_剑指Offer;

import java.util.Arrays;

public class _29_剑指Offer顺时针打印矩阵 {


    public static void main(String[] args) {

        _29_剑指Offer顺时针打印矩阵 v = new _29_剑指Offer顺时针打印矩阵();

        int[][] ins = {
                {7},
                {9},
                {6},
        };

        int[] ints = v.spiralOrder(ins);
        System.out.println(Arrays.toString(ints));
    }

    public int[] spiralOrder(int[][] matrix) {
        int row = matrix.length;
        if (row == 0) return new int[0];
        int col = matrix[0].length;
        if (col == 0) return new int[0];
        int[] results = new int[row * col];
        int index = 0;
        int left = 0;
        int right = col - 1;
        int top = 0;
        int bottom = row - 1;
        // 循环打印数据
        while (left <= right && top <= bottom) {
            // 左右遍历
            for (int i = left; i <= right; i++) {
                results[index++] = matrix[top][i];
            }
            top++;
            // 判断是否
            if (top > bottom) break;
            // 上下遍历
            for (int i = top; i <= bottom; i++) {
                results[index++] = matrix[i][right];
            }
            right--;
            if (right < left) break;
            // 右左遍历
            for (int i = right; i >= left; i--) {
                results[index++] = matrix[bottom][i];
            }
            bottom--;
            if (bottom < top) break;
            // 下上遍历
            for (int i = bottom; i >= top; i--) {
                results[index++] = matrix[i][left];
            }
            left++;
        }
        return results;
    }

}
